<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="130px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="供应商名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入供应商名称"/>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="供应商编码" prop="code">
            <el-input v-model="form.code" placeholder="请输入供应商编码" :disabled="!!form.id"/>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="供应商状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择供应商状态">
              <el-option label="停用" :value="0"/>
              <el-option label="启用" :value="1"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="说明" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入说明"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="client服务器信息" prop="clientInfoId">
            <el-select v-model="form.clientInfoId" placeholder="请选择client服务器信息" :disabled="!!form.id">
              <el-option v-for="item in cmppClientInfoList" :key="item.id" :label="item.serverIp+':'+item.serverPort" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="关联公司" prop="corporateId">
            <el-select v-model="form.corporateId" placeholder="请选择关联公司" :disabled="!!form.id">
              <el-option v-for="item in allCorporateList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="接入程序" prop="apiProgramId" >
            <el-select v-model="form.apiProgramId" placeholder="请选择接入程序" @change="getProvApiProgramTemplateList" :disabled="!!form.id">
              <el-option v-for="item in provApiProgramList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 动态模板字段区域 - 添加样式区分 -->
        <el-col :span="24" class="template-fields-section">
          <el-divider content-position="left">接入程序模板字段</el-divider>
          <el-col
              :span="24"
              class="mb20 template-field-item"
              v-for="item in provApiProgramTemplateList"
              :key="item.id">
            <el-form-item
                :label="item.argName"
                :prop="'templateFields.' + item.fieldName"
                :rules="item.required ? [{required: true, message: `${item.argName }不能为空`, trigger: 'blur'}] : []">
              <el-input
                  v-model="form.templateFields[item.fieldName]"
                  :placeholder="'请输入' + (item.argName )"
                  :title="item.remark"/>
            </el-form-item>
          </el-col>
        </el-col>


      </el-row>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="providerProviderDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from "/@/hooks/message";
import {getObj, addObj, putObj, newProvider} from '/@/api/bms/provider/provider'
import {rule} from '/@/utils/validate';
import {allProvApiProgram} from "/@/api/bms/provider/apiProgram";
import {getListByApiProgramId} from "/@/api/bms/provider/apiProgramTemplate";
import {allCmppClientInfo} from "/@/api/bms/provider/cmppClientInfo";
import {allCorporates} from "/@/api/bms/provider/corporate";

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const {prov_provider_status} = useDict('prov_provider_status')

// 提交表单数据
const form = reactive({
  id: '',
  name: '',
  code: '',
  status: 1,
  remark: '',
  apiProgramId: '',
  clientInfoId: '',
  corporateId: '',
  templateFields: {} // 确保这个对象存在
});

// 定义校验规则
const dataRules = ref({
  name: [{required: true, message: '供应商名称不能为空', trigger: 'blur'}],
  code: [{required: true, message: '供应商编码不能为空', trigger: 'blur'}],
  status: [{required: true, message: '供应商状态(0=停用,1=启用)不能为空', trigger: 'blur'}],
  remark: [{required: true, message: '说明不能为空', trigger: 'blur'}],
  apiProgramId: [{required: true, message: '接入程序id不能为空', trigger: 'blur'}],
  clientInfoId: [{required: true, message: 'client服务器信息不能为空', trigger: 'blur'}],
  corporateId: [{required: true, message: '关联公司不能为空', trigger: 'blur'}],
})

//接入方式
const provApiProgramList = ref([])

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });



  getAllProvApiProgram()
  getAllCorporateList()
  getCmppClientInfoList()
  // 获取provProvider信息
  if (id) {
    form.id = id
    getProvProviderData(id)
  }else{
    newProvider().then((res: any) => {
      Object.assign(form, res.data)
      //如果是新增，默认选择CMPP2.0,动态模板也刷新
      form.apiProgramId = '1'
      getProvApiProgramTemplateList('1')
    })




  }


};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getProvProviderData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    //获取
    getProvApiProgramTemplateList(res.data.apiProgramId);

    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
//获取接入程序列表
const getAllProvApiProgram = async () => {
  const res = await allProvApiProgram()
  console.log("getAllProvApiProgram---", res)
  provApiProgramList.value = res.data
}

//获取接入程序模板列表
const provApiProgramTemplateList = ref([])
const getProvApiProgramTemplateList = async (apiProgramId: string) => {
  const res = await getListByApiProgramId(apiProgramId)
  console.log("getProvApiProgramTemplateList---", res)
  provApiProgramTemplateList.value = res.data
}
//获取clientInfo列表
const cmppClientInfoList = ref([])
const getCmppClientInfoList = async () => {
  const res = await allCmppClientInfo()
  console.log("getCmppClientInfoList---", res)
  cmppClientInfoList.value = res.data
}

//获取上游公司列表
const allCorporateList = ref([])
const getAllCorporateList = async () => {
  const res = await allCorporates()
  console.log("getAllCorporateList---", res)
  allCorporateList.value = res.data
}


</script>
<style scoped>
.template-fields-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
  border: 1px dashed #e0e0e0;
}

.template-field-item {
  padding: 10px;
  background-color: white;
  border-radius: 4px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.template-field-item:hover {
  background-color: #f5f7fa;
}

.el-divider {
  margin: 10px 0 20px 0;
}
</style>
